package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZNativePlace;
import com.sec.etech.employeesync.mapper.OrgEmployeeZNativePlaceMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class NativePlaceConfigHandler implements ConfigTableHandler<OrgEmployeeZNativePlace> {

    @Resource
    private OrgEmployeeZNativePlaceMapper nativePlaceMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZNativePlace nativePlace = getEntityByName(name);
        if (nativePlace == null) {
            nativePlace = new OrgEmployeeZNativePlace();
            nativePlace.setCode(generateNextCode());
            nativePlace.setName(name);
            nativePlace.setActive(1);
            insertEntity(nativePlace);
            log.info("新增籍贯配置:name={}", name);
        }
        return nativePlace.getNativePlaceId();
    }

    @Override
    public OrgEmployeeZNativePlace getEntityByName(String name) {
        return nativePlaceMapper.selectOne(Wrappers.<OrgEmployeeZNativePlace>lambdaQuery()
                .eq(OrgEmployeeZNativePlace::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZNativePlace politics = nativePlaceMapper.selectOne(Wrappers.<OrgEmployeeZNativePlace>lambdaQuery()
                .orderByDesc(OrgEmployeeZNativePlace::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZNativePlace::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZNativePlace entity) {
        nativePlaceMapper.insert(entity);
    }
}
